Aug 24, 2023
Create a directory named “static” at the project’s root directory. This directory will hold static files that are shared across different apps within your project.
settings.py file, define the URL and directory for serving static files:Here, STATIC_URL is the URL prefix for serving static files, and STATICFILES_DIRS points to the directory where your project-level static files are stored.
myapp/
├── static/ # App-level static files directory
│ ├── myapp/
│ │ ├── css/
│ │ │ ├── app_styles.css
│ │ ├── js/
│ │ │ ├── app_script.js
│ │ ├── img/
│ │ │ ├── app_logo.pngTo use static files in your templates, load the {% static %} template tag. For example, in an HTML template:
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
<script src="{% static 'js/script.js' %}"></script>
<img src="{% static 'img/logo.png' %}" alt="Logo">{% static %} template tag generates the URL for the static file based on the configured STATIC_URL and the path you provide.staticdemo/settings.py):staticapp), create a new directory named static:static directory, create subdirectories for your static files:image.png
Place a CSS file (styles.css) and an image file (logo.png) inside their respective directories.
/* styles.css */
/* Body styles */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
/* Header styles */
h1 {
color: #333;
text-align: center;
padding: 20px;
background-color: #3ab1cc;
margin: 0;
}
/* Image styles */
img {
display: block;
margin: 0 auto;
max-width: 100%;
height: auto;
padding: 20px;
}staticdemo/urls.py)staticapp/urls.py):staticapp/views.py):Create a directory named templates within the staticapp app directory (staticapp/templates/). Inside the templates directory, create a file named index.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Static Demo</title>
<link rel="stylesheet" type="text/css" href="{% static 'staticapp/css/styles.css' %}">
</head>
<body>
<h1>Static Files Demo</h1>
<img src="{% static 'staticapp/img/logo.png' %}" alt="Logo" width="200" height="100">
</body>
</html>http://127.0.0.1:8000/static_demo/.styles.css file and displaying the image from the img directory.Manish Patel